import {
  Inject,
  Controller,
  Get,
  Post,
  Files,
  Query,
  Fields,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { PREFIX } from '../contanst';
import { BaseController } from './base.controller';
import { FileService } from '../service/file.service';
import { EXCEL_MAP } from '../contanst/teamLeaderServiceFee';
import { TeamLeaderServiceFeeService } from '../service/teamLeaderServiceFee.service';
import { toLower } from 'lodash';

const DESCRIPTION = '团长服务费';

@Controller(PREFIX)
export class APIController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  teamLeaderServiceFeeService: TeamLeaderServiceFeeService;

  @Get('/teamLeaderServiceFee', {
    description: `${DESCRIPTION}列表`,
  })
  async index(@Query('size') size = 10, @Query('page') page = 1) {
    const list = await this.teamLeaderServiceFeeService.page({
      data: { size, page },
    });
    return this.success(list);
  }

  @Inject()
  file: FileService;

  @Post('/teamLeaderServiceFee/import', {
    description: `${DESCRIPTION}导入`,
  })
  async import(
    @Files() files,
    @Fields('data_date') data_date,
    @Fields('store_name') store_name
  ) {
    const file = files[0];
    const data: any = await this.file.importExcel(file);
    const tableData = data?.[0]?.data;
    const tableHeader = tableData?.[0];
    const tableBody = tableData?.splice?.(1);
    const obj = {};
    Object.keys(EXCEL_MAP).forEach(key => {
      const index = tableHeader?.findIndex?.(
        item => toLower(item).trim() === toLower(key).trim()
      );
      obj[EXCEL_MAP[key]] = index;
    });
    const records: any[] = [];
    tableBody.forEach(item => {
      const record: any = {};
      Object.keys(obj).map(key => {
        record[key] = item[obj[key]]?.replace?.(/\t/g, '') || item[obj[key]];
        if (key === 'service_fee') {
          record[key] = Number(record[key]);
        }
      });
      record.store_name = store_name;
      record.data_date = data_date;
      records.push(record);
    });
    this.teamLeaderServiceFeeService.upsert(records);
    return this.success();
  }
}
